/*
 * @Description: Table Hooks
 * @Date: 2024-9-18 21:10:53
 * @Author: guoliu
 */
import { useEffect, useState } from "react";
import type { PaginationProps } from 'antd';

export default function useTableData(Func: any, searchForm: any, otherParams?: object) {
    const [isLoading, setIsLoading] = useState(false);
    const showTotal: PaginationProps['showTotal'] = total => `共 ${total} 条`;
    const [pageInfo, setPageInfo] = useState({
        pageSize: 10,
        pageNo: 1,
        total: 0,
        showTotal: showTotal
    });
    const [searchParams, setSearchParams] = useState<any>({});
    const [dataSource, setDataSource] = useState([]);
    const defaultFormat = (data: any) => data;
    const onChangeTable = (formatParams = defaultFormat) => {
        const params = searchForm?.getFieldsValue()
        setSearchParams({
            ...searchParams,
            ...otherParams,
            ...formatParams(params)
        })
        setPageInfo({
            ...pageInfo,
            pageNo: 1
        })
    }
    const getTableData = async () => {
        setIsLoading(true);
        const res =  await Func({
            ...pageInfo,
            ...searchParams,
            ...otherParams
        })
        // console.log('--------res',res )
        if (res.list) {
            const totals = res.total||0;
            const showTotal: PaginationProps['showTotal'] = total => `Total ${total} items`;
            setDataSource((res.list || res.records) ?? [])
            setPageInfo({
                ...pageInfo,
                total: totals,
            })
            setIsLoading(false);
        } else {
            setIsLoading(false);
        }
    }
    useEffect(() => {
        getTableData()
    }, [pageInfo.pageSize, pageInfo.pageNo, searchParams]);
    return {
        isLoading,
        searchParams,
        setSearchParams,
        dataSource,
        pageInfo,
        setPageInfo,
        getTableData,
        onChangeTable
    }
}